package com.xuhuan.juc.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author huan.xu
 * @Date 2021/12/28 18:59
 * @Description 线程精确通知顺序访问
 * 多线程之间按顺序调用，实现A->B->C
 * 三个线程启动，要求如下:
 * AA打印5次，BB打印10次， CC打印15次
 * 接着
 * AA打印5次，BB打印10次， CC打印15次
 * 来10轮
 */
public class ThreadOrderAccess {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResource.printA();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResource.printB();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                shareResource.printC();
            }
        }, "C").start();

    }
}

@Slf4j
class ShareResource {
    /**
     * 标志位：1：A 2：B 3：C
     */
    private int number = 1;
    private Lock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    public void printA() {
        lock.lock();
        try {
            //1.判断
            while (number != 1) {
                conditionA.await();
            }
            //2.干活
            for (int i = 0; i < 5; i++) {
                log.info("{}\t{}", Thread.currentThread().getName(), i + 1);
            }
            //3.通知
            number = 2;
            conditionB.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            while (number != 2) {
                conditionB.await();
            }
            for (int i = 0; i < 10; i++) {
                log.info("{}\t{}", Thread.currentThread().getName(), i + 1);
            }
            number = 3;
            conditionC.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            while (number != 3) {
                conditionC.await();
            }
            for (int i = 0; i < 15; i++) {
                log.info("{}\t{}", Thread.currentThread().getName(), i + 1);
            }
            number = 1;
            conditionA.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}